package com.code.penguin.managers;

import com.alibaba.fastjson.JSON;
import com.code.penguin.models.ClientResponse;
import com.google.common.collect.Maps;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

/**
 * http调用的相关管理类
 *
 * @author xiaoyaowang
 */
@Component
public class HttpManager {

    private static Logger log = LoggerFactory.getLogger(HttpManager.class);

    private static final String ACCEPT = "Accept";

    @Value("${whiteCoinBrowser.url}")
    private String whiteCoinBrowserUrl;

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 校验相关币种地址
     *
     * @param coinAddress 币种地址
     * @return 币种地址验证结果
     */
    public Boolean verifyCoinAddress(String coinAddress) {
        if (StringUtils.isBlank(coinAddress)) {
            return false;
        }
        //设置请求参数
        Map<String, Object> postData = Maps.newHashMapWithExpectedSize(1 << 4);
        postData.put("addr", coinAddress);
        String requestBody = JSON.toJSONString(postData);
        log.info("请求体数据：【{}】", requestBody);
        HttpEntity<String> formEntity = new HttpEntity<>(requestBody, getJsonHeader());
        HttpMethod method = HttpMethod.POST;
        ResponseEntity<ClientResponse> response = restTemplate.exchange(whiteCoinBrowserUrl + "xwcAddressWhetherExist", method, formEntity, ClientResponse.class);
        log.info("校验钱包地址的响应结果:{}", JSON.toJSONString(response));
        ClientResponse body = response.getBody();
        if (null != body) {
            Integer rtnCode = body.getRetCode();
            if (null != rtnCode && rtnCode == 200) {
                Object data = body.getData();
                boolean verifyResult = (boolean) data;
                log.info("地址验证结果：【{}】", verifyResult);
                return verifyResult;
            } else {
                return false;
            }
        }
        return false;
    }


    /**
     * 构造http请求的头部信息
     *
     * @return http头部信息
     */
    private HttpHeaders getJsonHeader() {
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        headers.add(ACCEPT, MediaType.APPLICATION_JSON.toString());
        return headers;
    }

}
